﻿using MDReader.Control;
using MDReader.Helper;
using MDReader.Script.Toolstrips.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MDReader.Script.Toolstrips
{
    public class tool_021_AddCode : toolBaseCtrlEditor
    {
        public tool_021_AddCode(ILog log)
        {
            logger = log;
        }
        private ILog logger;

        public override string ShowName => "代码";
        public override string Description => "把选中的内容设为代码区域";

        protected override void CtrlEditorToolstripItem_ClickAfter(ICtrlEditorResource me)
        {

            if (me.getTxtSource != null)
            {

                try
                {
                    RichTextBox txtSource = me.getTxtSource();
                    // 获取当前选中的文本
                    string selectedText = txtSource.SelectedText;
                    if (!string.IsNullOrEmpty(selectedText))
                    {
                        // 如果当前选中了文本，那么给这段文本增加代码标识
                        int selectionStart = txtSource.SelectionStart;
                        string modifiedText = $"```\n{selectedText}\n```";
                        txtSource.SelectedText = modifiedText;
                        txtSource.Select(selectionStart + 4, modifiedText.Length - 8);
                    }
                    else
                    {
                        // 如果当前没选中文本，那么原地插入一个代码段
                        int caretPosition = txtSource.SelectionStart;
                        txtSource.Select(caretPosition, 0);
                        string modifiedText = $"```\n\n```";
                        txtSource.SelectedText = modifiedText;
                        txtSource.Select(caretPosition + 4, modifiedText.Length - 8);
                    }
                }
                catch (Exception ex)
                { logger?.WriteExceptionToEventLog(ex); }

            }

        }
    }
}
